﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GoodMan.Infrastructure.Entities.Entity;
using GoodMan.Infrastructure.Entities;
using System.Data.SqlClient;
using System.Data;
using GoodMan.Infrastructure.Entities.Repository;

namespace GoodMan.Portal.Biz
{
    public class RecommendedBiz
    {
        public static ItemListBox<Product> GetAllRecommendedProducts(string productkey, int page, int pagesize)
        {
            //var count = new Product().Count(c => (c.ProductType == categoryId || categoryId == 0) && (c.ProductSubType == subcategoryId || subcategoryId == 0) && (c.ProductName.Contains(productkey) || c.ProductCode.Contains(productkey)));
            var count = 0;
            using (Context ctx = new Context())
            {
                count = (from c in ctx.Product
                         join d in ctx.SpecialSale
                         on c.Id equals d.ProductId
                         where c.ProductName.Contains(productkey) || c.ProductCode.Contains(productkey)
                         select new { c, d }).Count();
            }
            using (Context ctx = new Context())
            {
                string sql = @"select top (@pagesize) t.* from (select ROW_NUMBER() OVER (ORDER BY b.createdate desc) AS RowNumber, a.*,d.Price,
                            case when e.Price is null then d.Price else e.price end as policyprice
                             from T_Product a
                            inner join dbo.T_recommended b on a.Id=b.productid
                            inner join (select * from dbo.T_Policy c where c.PolicyType=1) d 
                            on a.Id=d.ProductId
                            left join (select top 1 * from dbo.T_Policy c where c.IsActive=1 and c.PolicyType=2 and GETDATE() between c.StartDate and c.ExpireDate) e 
                            on a.Id=e.ProductId 
                            where a.areacode=1 and a.ProductCode like '%'+@productkey+'%' or a.ProductName like '%'+@productkey+'%') t
                            where t.RowNumber>@pagesize*@page";

                var datatable = ctx.ExcuteSQL(sql,
                     new SqlParameter("@productkey", productkey),
                      new SqlParameter("@pagesize", pagesize),
                     new SqlParameter("@page", page)
                    );

                List<Product> data = null;
                if (datatable != null && datatable.Rows.Count > 0)
                {
                    var datetime = DateTime.Now;
                    data = new List<Product>();
                    foreach (DataRow row in datatable.Rows)
                    {
                        var product = new Product()
                        {
                            CreateDate = Convert.ToDateTime(row["CreateDate"].ToString()),
                            Id = int.Parse(row["Id"].ToString()),
                            Images = (row["Images"].ToString() != null&&row["Images"].ToString() !="") ? row["Images"].ToString().Split(';')[0] : "",
                            ProductCode = row["ProductCode"].ToString(),
                            ProductName = row["ProductName"].ToString(),
                            PurchasePrice = decimal.Parse(row["PurchasePrice"] != null ? row["PurchasePrice"].ToString() : "0"),
                            DefaulSalePrice = decimal.Parse(row["Price"] != null ? row["Price"].ToString() : "0"),
                            PolicyPrice = decimal.Parse(row["policyprice"] != null ? row["policyprice"].ToString() : "0")
                        };
                        data.Add(product);
                    }
                }
                var list = new ItemListBox<Product>(data).BuildPage(
                    count, page, pagesize, new PageParameter() { Style = "workspace" });
                return list;
            }

        }

        public static bool DelRecommended(int productid)
        {
            try
            {
                using (Context ctx = new Context())
                {
                    ctx.Delete<T_Recommended>()
                        .WhereSet(c => c.ProductId, WhereOperator.Equal, productid)
                        .End()
                        .Excute();
                }

                return true;
            }
            catch (Exception ex)
            {
                //日志记录
                return false;
            }
            return false;
        }

        public static bool IsRecommended(int productId)
        {
           return new Recommended().Find(c => c.ProductId == productId)!=null;
             
        }
    }
}
